package com.beidouin.GnssMain.sample;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.common.EnvironmentUtilities;
import com.baidu.mapapi.map.offline.MKOLSearchRecord;
import com.baidu.mapapi.map.offline.MKOLUpdateElement;
import com.baidu.mapapi.map.offline.MKOfflineMap;
import com.baidu.mapapi.map.offline.MKOfflineMapListener;
import com.beidouin.GnssMain.R;
import com.beidouin.GnssMain.models.SysParam;
import com.beidouin.GnssMain.sample.LxActivity;
import com.beidouin.GnssMain.utils.OnItemClickLinstener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

public class OfflineDemo extends Activity  {
    private static final String TAG = "OfflineDemo";

    private MKOfflineMap mOffline = null;
    private TextView cidView;
    private TextView stateView;
    private EditText cityNameView;
    private int mCityid;

    /**
     * 已下载的离线地图信息列表
     */
    private List<MKOLUpdateElement> localMapList = null;
    private LocalMapAdapter lAdapter = null;
    private ArrayList<MKOLSearchRecord> records;
    //    public ArrayList<Integer> integers = new ArrayList<>();//存城市id
    private SharedPreferences preferences;
    private SharedPreferences.Editor edit;
    private ListView localMapListView;
    private TextView ratio;//下载进度
    private String FILE_NAME;
    //    private static ArrayList<Integer> allcitys = new ArrayList<>();
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            updateView();
        }
    };
    private ArrayList<String> allCities;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_offline_demo);

        //设置路径
        String filepath = getSdCardPath() + SysParam.foldername;
        if (isDirectionExist(filepath) == false) {
            return;
        }
        //放到SD卡中
        EnvironmentUtilities.setSDCardPath(filepath);
        mOffline = new MKOfflineMap();
        mOffline.init(new MKOfflineMapListener() {

            @Override
            public void onGetOfflineMapState(int type, int state) {
                switch (type) {
                    case MKOfflineMap.TYPE_DOWNLOAD_UPDATE: {
                        MKOLUpdateElement update = mOffline.getUpdateInfo(state);
                        // 处理下载进度更新提示
                        if (update != null) {
                            Log.e("离线地图进度:", state + "");
//                            stateView.setText(String.format("%s : %d%%", update.cityName,
//                                    update.ratio));
                            handler.sendEmptyMessageDelayed(0, 100);

                        }
                    }
                    break;
                    case MKOfflineMap.TYPE_NEW_OFFLINE:
                        // 有新离线地图安装
                        Log.d("OfflineDemo", String.format("add offlinemap num:%d", state));
                        break;
                    case MKOfflineMap.TYPE_VER_UPDATE:
                        // 版本更新提示
                        // MKOLUpdateElement e = mOffline.getUpdateInfo(state);
                        break;
                    default:
                        break;
                }
            }
        });
        initView();
    }
    public boolean isSdCardExist() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }
    //判断文件夹是否存在,如果不存在则创建文件夹
    public boolean isDirectionExist(String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();

        }
        return file.exists();
    }
    //获取SD卡根目录
    public String getSdCardPath() {
        String sdpath = "";
        if (isSdCardExist()) {
            File file = Environment.getExternalStorageDirectory();
            sdpath = Environment.getExternalStorageDirectory()
                    .getAbsolutePath();
        } else {
            sdpath = "";
        }
        return sdpath;
    }
    boolean isClick = false;

    private void initView() {

        cidView = (TextView) findViewById(R.id.cityid);
        cityNameView = (EditText) findViewById(R.id.city);
//        stateView = (TextView) findViewById(R.id.state);

        // 获取热闹城市列表
        ArrayList<MKOLSearchRecord> records1 = mOffline.getHotCityList();
        ListView allCityList = (ListView) findViewById(R.id.allcitylist);
        // 获取所有支持离线地图的城市
        allCities = new ArrayList<String>();
        final ArrayList<String> allCityNames = new ArrayList<String>();
        ArrayList<MKOLSearchRecord> records2 = mOffline.getOfflineCityList();

        if (records1 != null) {
            for (MKOLSearchRecord r : records2) {
                //V4.5.0起，保证数据不溢出，使用long型保存数据包大小结果
                allCities.add(r.cityName + "(" + r.cityID + ")" + "   --"
                        + this.formatDataSize(r.dataSize));
                allCityNames.add(r.cityName);
                Log.e("离线地图当前城市list：", r.toString() + "");

            }
        }
        ListAdapter aAdapter = (ListAdapter) new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, allCities) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                TextView textView = (TextView) view.findViewById(android.R.id.text1);
//                textView.setTextColor(SkinCompatResources.getColor(OfflineDemo.this, R.color.activity_textcolor));
                return view;
            }
        };
        allCityList.setAdapter(aAdapter);
        //全国城市
        allCityList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                cityNameView.setText(allCityNames.get(i));

                ArrayList<MKOLSearchRecord> allCityName = mOffline.searchCity(allCityNames.get(i));

                if (allCityName == null || allCityName.size() != 1) {
                    Toast.makeText(OfflineDemo.this, "不支持该城市离线地图", Toast.LENGTH_SHORT).show();
                    return;
                }
                cidView.setText(String.valueOf(allCityName.get(0).cityID));
                mCityid = allCityName.get(0).cityID;
                Log.i("mCityid", "===========" + mCityid);
                int cityid = Integer.parseInt(cidView.getText().toString());
                mOffline.start(cityid);
                Toast.makeText(OfflineDemo.this, "开始下载离线地图：" + allCityName.get(0).cityName, Toast.LENGTH_SHORT).show();
                updateView();
            }
        });
        // 获取已下过的离线地图信息
        localMapList = mOffline.getAllUpdateInfo();
        if (localMapList == null) {
            localMapList = new ArrayList<MKOLUpdateElement>();
        }

        localMapListView = (ListView) findViewById(R.id.localmaplist);
        lAdapter = new LocalMapAdapter(new OnItemClickLinstener() {

            @Override
            public void onItemClick(View view, int position, int flag) {
                if (flag == 0 && position < lAdapter.getCount()) {
                    mOffline.pause(localMapList.get(position).cityID);
                    mOffline.remove(localMapList.get(position).cityID);
                    handler.sendEmptyMessageDelayed(0, 500);
                }
                isClick = false;
            }
        });


        localMapListView.setAdapter(lAdapter);

        //下载管理里面的条目
        localMapListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            }
        });
    }



    /**
     * 搜索离线需市
     *
     * @param view
     */
    public void search(View view) {
        ArrayList<MKOLSearchRecord> records = mOffline.searchCity(cityNameView.getText().toString());
        if (records == null || records.size() != 1) {
            Toast.makeText(this, "不支持该城市离线地图", Toast.LENGTH_SHORT).show();
            return;
        }
        cidView.setText(String.valueOf(records.get(0).cityID));
        mCityid = records.get(0).cityID;
        Log.e("离线地图当前城市编码：", records.get(0).cityID + "");

        int cityid = Integer.parseInt(cidView.getText().toString());
        mOffline.start(cityid);

        Toast.makeText(this, "开始下载离线地图", Toast.LENGTH_SHORT)
                .show();
        updateView();
    }


    /**
     * 开始下载
     *
     * @param view
     */
    public void start(View view) {

        for (int i = 0; i < localMapList.size(); i++) {
            mOffline.start(localMapList.get(i).cityID);
            updateView();
        }
        Toast.makeText(this, "开始下载离线地图请勿退出:", Toast.LENGTH_SHORT).show();
    }

    /**
     * 暂停下载
     *
     * @param view
     */
    public void stop(View view) {

        for (int i = 0; i < localMapList.size(); i++) {
            mOffline.pause(localMapList.get(i).cityID);
            updateView();
        }
        Toast.makeText(this, "暂停全部下载离线地图", Toast.LENGTH_SHORT).show();
    }

    /**
     * 删除离线地图
     *
     * @param view
     */
    public void remove(View view) {
        int cityid = Integer.parseInt(cidView.getText().toString());
        mOffline.remove(cityid);
        Toast.makeText(this, "删除离线地图. cityid: " + cityid, Toast.LENGTH_SHORT).show();
        updateView();
    }

    /**
     * 更新状态显示
     */
    public void updateView() {
        //  localMapList= mOffline.getAllUpdateInfo();
        localMapList = mOffline.getAllUpdateInfo();
        if (localMapList == null) {
            localMapList = new ArrayList<MKOLUpdateElement>();
        }
        if (!isClick) {
            lAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        for (int i = 0; i < localMapList.size(); i++) {
            if (localMapList.get(i).ratio!=100) {
                Toast.makeText(this, "离线地图暂停下载", Toast.LENGTH_SHORT).show();
                break;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * V4.5.0起，保证数据不溢出，使用long型保存数据包大小结果
     */
    public String formatDataSize(long size) {
        String ret = "";
        if (size < (1024 * 1024)) {
            ret = String.format("%dK", size / 1024);
        } else {
            ret = String.format("%.1fM", size / (1024 * 1024.0));
        }
        return ret;
    }

    @Override
    protected void onDestroy() {
        /**
         * 退出时，销毁离线地图模块
         */
        for (int i = 0; i < localMapList.size(); i++) {
            mOffline.pause(localMapList.get(i).cityID);
        }
        super.onDestroy();
    }

    /**
     * 离线地图管理列表适配器
     */
    @SuppressLint("ClickableViewAccessibility")
    public class LocalMapAdapter extends BaseAdapter {
        private int defPos = -1;//默认
        private int mIndex = -1;//默认
        OnItemClickLinstener onItemClickLinstener;

        public LocalMapAdapter(OnItemClickLinstener onItemClickLinstener) {
            this.onItemClickLinstener = onItemClickLinstener;
        }

        public void setPos(int posion) {
            defPos = posion;
            this.notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return localMapList.size();
        }

        @Override
        public Object getItem(int index) {
            return localMapList.get(index);
        }

        @Override
        public long getItemId(int index) {
            return index;
        }

        @Override
        public View getView(int index, View view, ViewGroup arg2) {
            MKOLUpdateElement e = (MKOLUpdateElement) getItem(index);
            view = View.inflate(OfflineDemo.this, R.layout.offline_localmap_list, null);
            mIndex = index;
            initViewItem(view, e, index);
            return view;
        }

        boolean isStart = false;

        public void initViewItem(View view, final MKOLUpdateElement e, final int index) {
            Button display = (Button) view.findViewById(R.id.display);
//            Button start = (Button) view.findViewById(R.id.start);
            final Button remove = (Button) view.findViewById(R.id.remove);
            TextView title = (TextView) view.findViewById(R.id.title);
            TextView update = (TextView) view.findViewById(R.id.update);
            ratio = (TextView) view.findViewById(R.id.ratio);
            ratio.setText(e.ratio + "%");
            title.setText(e.cityName);

//            if (defPos != -1) {
//                if (defPos == index) {
//                    if (isStart) {
//                        start.setText("暂停");
//                    } else {
//                        start.setText("开始");
//                    }
//                }
//            }
            if (e.update) {
                update.setText("可更新");

                mOffline.start(localMapList.get(index).cityID);
            } else {
                update.setText("最新");
            }
            if (e.ratio != 100) {
                display.setEnabled(false);
            } else {
                display.setEnabled(true);
            }
         /*   start.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (isStart) {
                        isStart = false;
                        int cityid = Integer.parseInt(cidView.getText().toString().trim());
                        mOffline.pause(cityid);
                        Toast.makeText(OfflineDemo.this, "暂停下载离线地图. cityid: " + cityid, Toast.LENGTH_SHORT).show();
                        setPos(mIndex);
                        updateView();
                    } else {
                        isStart = true;
                        setPos(mIndex);
                        int cityid = Integer.parseInt(cidView.getText().toString().trim());
                        mOffline.start(cityid);
                        Toast.makeText(OfflineDemo.this, "开始下载离线地图. cityid: " + cityid, Toast.LENGTH_SHORT).show();
                        updateView();
                    }
                }
            });*/


            remove.setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {

                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            isClick = true;
                            Log.i(TAG, "Item: ACTION_DOWN");
                            break;
                        case MotionEvent.ACTION_MOVE:
                            Log.i(TAG, "Item: ACTION_MOVE");
                            break;
                        case MotionEvent.ACTION_UP:
                            Log.i(TAG, "Item: ACTION_UP");
                            isClick = false;
                            break;
                        case MotionEvent.ACTION_CANCEL:
                            isClick = false;
                            Log.i(TAG, "Item: ACTION_CANCEL");
                            break;
                    }

                    return false;
                }
            });

            display.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            isClick = true;
                            Log.i(TAG, "Item: ACTION_DOWN");
                            break;
                        case MotionEvent.ACTION_MOVE:
                            Log.i(TAG, "Item: ACTION_MOVE");
                            break;
                        case MotionEvent.ACTION_UP:

                            break;
                        case MotionEvent.ACTION_CANCEL:
                            isClick = false;
                            Log.i(TAG, "Item: ACTION_CANCEL");
                            break;
                    }
                    return false;
                }
            });


            remove.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    if (onItemClickLinstener != null) {
                        onItemClickLinstener.onItemClick(remove, index, 0);
                    }
                }
            });
            display.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.putExtra("customStyle", true);
                    intent.putExtra("x", e.geoPt.longitude);
                    intent.putExtra("y", e.geoPt.latitude);
                    intent.putExtra("level", 13.0F);
                    intent.setClass(OfflineDemo.this, LxActivity.class);
                    startActivity(intent);
                    isClick = false;
                }
            });
        }
    }
}